package cn.kawa.searchMsg.service.impl;

import cn.kawa.basic.exception.BusinessException;
import cn.kawa.basic.service.IBaiduAiAuditService;
import cn.kawa.basic.service.impl.BaseServiceImpl;
import cn.kawa.basic.util.CodeGenerateUtils;
import cn.kawa.basic.util.DistanceUtils;
import cn.kawa.basic.util.PageList;
import cn.kawa.basic.util.Point;
import cn.kawa.order.domain.OrderPetAcquisition;
import cn.kawa.order.mapper.OrderPetAcquisitionMapper;
import cn.kawa.org.domain.Employee;
import cn.kawa.org.domain.Shop;
import cn.kawa.org.mapper.EmployeeMapper;
import cn.kawa.org.mapper.ShopMapper;
import cn.kawa.pet.domain.Pet;
import cn.kawa.pet.mapper.PetMapper;
import cn.kawa.searchMsg.domain.SearchMasterMsg;
import cn.kawa.searchMsg.domain.SearchMasterMsgAuditLog;
import cn.kawa.searchMsg.dto.AcceptDto;
import cn.kawa.searchMsg.mapper.SearchMasterMsgAuditLogMapper;
import cn.kawa.searchMsg.mapper.SearchMasterMsgMapper;
import cn.kawa.searchMsg.query.SearchMasterMsgQuery;
import cn.kawa.searchMsg.service.ISearchMasterMsgService;
import cn.kawa.user.domain.User;
import cn.kawa.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    /**
     * 用于发布寻主信息，并且按地理位置推荐给最近的店铺
     * 保存表格：SearchMasterMsg  涉及表格 ： user、 logininfo 、shop
     * @param searchMasterMsg
     * @param id
     */
    @Override
    public void publish(SearchMasterMsg searchMasterMsg, Long id) {
        //1.先添加到数据库   state=0 待审核
        searchMasterMsg.setNote("待审核");
        //思路 ::  set userId  shopId
        User user = userMapper.loadByLoginInfoId(id);
        searchMasterMsg.setUserId(user.getId());
        /**
         * 计算获得适合接单的店铺   shopId
         */
        Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
        Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
        searchMasterMsg.setShopId(nearestShop.getId());

        searchMasterMsgMapper.save(searchMasterMsg);
        //2.审核
        Boolean textAudit = baiduAiAuditService.textAudit(searchMasterMsg.getName()
                + searchMasterMsg.getTitle() + searchMasterMsg.getAddress());
        //Boolean imageAudit = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        if(textAudit ){//&& imageAudit
            //修改searchMasterMsg的信息并更新
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("已审核，待处理");
            searchMasterMsgMapper.update(searchMasterMsg);
            //添加审核日志
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setState(1);
            searchMasterMsgAuditLog.setNote("审核通过");
            searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);
        }else{
            //searchMasterMsg.setState(0);//默认0
            searchMasterMsg.setNote("请检查信息再重试");
            searchMasterMsgMapper.update(searchMasterMsg);
            //添加审核日志
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setState(0);
            searchMasterMsgAuditLog.setNote("信息驳回");
            searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);


            throw new BusinessException("信息审核不通过");
        }

    }

    /**
     * 改造查询分页数据的方法，添加高级查询的参数以及映射的的表格
     * @param query
     * @param id
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> queryPageMsg(SearchMasterMsgQuery query, Long id) {
        //通过loginInfo id 查询employee ,再通过emp获取shopid
        Employee emp = employeeMapper.loadByLogininfoId(id);
        // 待处理状态
        //query.setState(1);
        if(emp.getShop_id()!=null){
            query.setShopId(emp.getShop_id());
        }
        return super.queryPage(query);

    }
    /**
     * 用于商户拒单
     * @param smmId
     */
    @Override
    public void reject(Long smmId) {
        SearchMasterMsg byId = searchMasterMsgMapper.loadById(smmId);
        byId.setShopId(null);
        searchMasterMsgMapper.update(byId);
    }


    /**
     * 用于商户接单
     * @param acceptDto
     * @param id
     */
    @Override
    public void accept(AcceptDto acceptDto, Long id) {
        //从acceptDto取值
        Long empId = acceptDto.getHandler();//用于想起发送短信
        Long msgId = acceptDto.getMsgId();
        String note = acceptDto.getNote();//用于存入数据库
        //根据id（smmid）查询订单： 判断订单是否被重复接单
        OrderPetAcquisition orderTmp = orderPetAcquisitionMapper.loadByMsgId(msgId);
        if (orderTmp!=null){
            throw new BusinessException("已经被接单，正在处理中！");
        }
        //1.生成pet并保存：根据SearchMasterMsg生成,通过acceptDto.msgId获取根据SearchMasterMsg生成
        SearchMasterMsg byId = searchMasterMsgMapper.loadById(msgId);
        /**
         * 获取pet对象
         */
        Pet pet = searchMasterMsg2pet(byId);
        petMapper.save(pet);
        //2.生成收购订单并保存：根据pet和acceptDto生成
        OrderPetAcquisition orderPetAcquisition = createOrderPetAcquisition(acceptDto,pet,byId);
        orderPetAcquisitionMapper.save(orderPetAcquisition);


    }

    private OrderPetAcquisition createOrderPetAcquisition(AcceptDto dto, Pet pet,SearchMasterMsg smm) {

        // 创建一个订单对象，赋值
        OrderPetAcquisition order = new OrderPetAcquisition();

        // 随机生成一个订单编号
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(smm.getUserId()));
        // 摘要
        order.setDigest("【"+smm.getTitle()+"】");
        // 最后确认时间 定时任务
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));

        order.setState(0);// 待处理
        order.setPrice(smm.getPrice());
        order.setPetId(pet.getId());
        order.setUserId(smm.getUserId());
        order.setShopId(smm.getShopId());
        order.setAddress(smm.getAddress());
        order.setEmpId(dto.getHandler());
        order.setSearchMasterMsgId(dto.getMsgId());
        return order;
    }

    private Pet searchMasterMsg2pet(SearchMasterMsg smm) {
        Pet pet = new Pet();
        pet.setName(smm.getName());
        pet.setCostprice(smm.getPrice());
        pet.setTypeId(smm.getPetType());
        pet.setResources(smm.getResources());
        pet.setShopId(smm.getShopId());
        pet.setSearchMasterMsgId(smm.getId());
        return pet;
    }


}
